import React from 'react';
import {
  Form, Icon, Input, Button,
} from 'antd';
import { withRouter } from 'react-router-dom';
import { setToken, getRole } from 'services/token';
import { auth } from 'services/user';

class LoginForm extends React.Component {
  handleSubmit = async (e) => {
    e.preventDefault();
    const { form, history } = this.props;

    try {
      // antd uses async validator
      await form.validateFields();
      const data = await auth(form.getFieldsValue());
      const { token } = data;
      // console.log(token);
      setToken(token);
      const role = getRole(token);
      // 0:运维人员 1:管理人员 2:工艺人员 3:操作人员
      const paths = ['operation/user', 'manage/monitor', 'process/design', 'operator/task'];
      history.push(paths[role]);
    } catch (err) {
      console.error(err);
    }
  };

  render() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <Form.Item>
          {getFieldDecorator('userId', {
            rules: [{ required: true, message: '请输入工号!' }],
          })(
            <Input
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="工号"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '请输入密码!' }],
          })(
            <Input
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="密码"
            />,
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
                      登录
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

const WrappedLoginForm = Form.create({})(LoginForm);

export default withRouter(WrappedLoginForm);
